//
//  DDPullDownView.swift
//  swift微博
//
//  Created by whitcast on 16/7/18.
//  Copyright © 2016年 whitcast. All rights reserved.
//

import UIKit
import SnapKit

enum pullState: Int {
    case pullDownToRefresh = 0
    case takeUpfingleToRefresh = 1
    case refreshing = 2
}
//下拉出现的view(下拉刷新)
class DDPullDownView: UIControl {
    //最初的contentInset
    var  originalinset: CGFloat = 0
    //view的高度
    var viewHeight: CGFloat = 50
    //状态  下拉刷新  松手刷新  正在刷新
    var viewState: pullState = .pullDownToRefresh {
        didSet{
            switch viewState {
                
            case .pullDownToRefresh:
                
                textLab.text = "下拉刷新"
                
                imgView.hidden = false
                //箭头回复原始位置
                UIView.animateWithDuration(0.025, animations: { () -> Void in
                    
                    self.imgView.transform = CGAffineTransformIdentity
                    
                })
                if oldValue == .refreshing {
                    
                    //                    self.theSuperView?.contentInset.top -= self.viewHeight
                    self.theSuperView?.contentInset.top -= 50
                }
                //停止菊花转
                activity.stopAnimating()
                
            case .takeUpfingleToRefresh:
                //停止菊花转
                activity.stopAnimating()
                
                imgView.hidden = false
                
                textLab.text = "松开手后刷新"
                //箭头转向
                UIView.animateWithDuration(0.025, animations: { () -> Void in
                    
                    self.imgView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                    
                })
            case .refreshing:
                //避免重复网络请求
                if activity.isAnimating() {
                    return
                }
                textLab.text = "正在加载"
                
                imgView.hidden = true
                
                activity.startAnimating()
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    //  self.theSuperView?.contentInset.top += self.viewHeight
                    
                    self.theSuperView?.contentInset.top += 50
                })
                //请求数据加载
                self.sendActionsForControlEvents(.ValueChanged)
                
            default:
                return
            }
            
        }
    }
    //父控件
    var theSuperView:  UIScrollView?
    
    //懒加载控件  箭头
    lazy var imgView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //文字标签
    lazy var textLab: UILabel = {
        let lab = UILabel()
        lab.text = "下拉刷新"
        lab.textColor = UIColor.grayColor()
        lab.font = UIFont.systemFontOfSize(14)
        return lab
        
    }()
    //菊花转
    lazy var activity: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
    
    override init(frame: CGRect) {
        super.init(frame:frame)
        //设置UI
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置UI
    private func setUpUI() {
        //背景颜色
        backgroundColor = UIColor.orangeColor()
        //添加控件
        addSubview(imgView)
        addSubview(activity)
        addSubview(textLab)
        //约束
        imgView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
        }
        activity.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self).offset(-35)
            make.centerY.equalTo(self)
            make.size.equalTo(CGSizeMake(40, 40))
        }
        textLab.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(imgView.snp_trailing)
            make.centerY.equalTo(imgView)
        }
        //        activity.startAnimating()
    }
    
    // MARK:-- 获取父控件 监听父控件的滚动
    override func willMoveToSuperview(newSuperview: UIView?){
        //获取父控件
        theSuperView = newSuperview as? UIScrollView
        
        originalinset = (theSuperView?.contentInset.top)!
        //监听父控件的滚动
        theSuperView?.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //获取父控件的滚动y值
        let y: CGFloat = -(theSuperView?.contentOffset.y)!

        //父控件滚动
//        if theSuperView?.dragging == true {
//            if y < viewHeight + (theSuperView?.contentInset.top)! && y > 0 {
//                //状态
//                viewState = .pullDownToRefresh
//                
//                print(viewState)
//            }else {
//                //状态
//                viewState = .takeUpfingleToRefresh
//                print(viewState)
//            }
//            
//        }else{
//            if y < viewHeight + (theSuperView?.contentInset.top)!  {
//                //                //状态
//                //                viewState = .pullDownToRefresh
//                //                print("下拉刷新")
//            }else {
//                if viewState == .takeUpfingleToRefresh{
//                    //状态
//                    viewState = .refreshing
//                    print(viewState)
//
//                }
//            }
//        }
          if theSuperView?.dragging == true {
            if y < viewHeight + (theSuperView?.contentInset.top)! && viewState == .takeUpfingleToRefresh{
                
                viewState = .pullDownToRefresh
            }else if(y >= viewHeight + (theSuperView?.contentInset.top)! && viewState == .pullDownToRefresh){
                viewState = .takeUpfingleToRefresh
            }
            
          }else {
            if viewState == .takeUpfingleToRefresh{
                viewState = .refreshing
            }
        }
        
        
    }
    
    
    
    deinit{
        //销毁监听者
        theSuperView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}
